package com.sakura.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sakura.common.R;
import com.sakura.dto.DishDto;
import com.sakura.pojo.Category;
import com.sakura.pojo.Dish;
import com.sakura.serivce.CategoryService;
import com.sakura.serivce.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto) {
        dishService.saveDishAndDishFlavor(dishDto);
        return R.success("上传成功");
    }

    @GetMapping("/page")
    public R<Page<DishDto>> page(@RequestParam("page") Integer page,
                                 @RequestParam("pageSize") Integer pageSize,
                                 @RequestParam(required = false, value = "name") String name) {

        // 添加dish分页页数条件
        Page<Dish> dishPage = new Page<>(page, pageSize);
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        // 判断是否有name，如果有则添加条件
        dishQueryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        dishQueryWrapper.orderByAsc("sort").orderByDesc("update_time");
        // 查询数据
        dishService.page(dishPage, dishQueryWrapper);

        // 开始导入数据到DTO
        ArrayList<DishDto> dishDtos = new ArrayList<>();
        List<Dish> records = dishPage.getRecords();
        Page<DishDto> dishDtoPage = new Page<>();
        // 复制除了records之外的数据，records单独处理
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        // 处理records
        for (Dish dish : records) {
            // 创建一个DTO用于暂存数据
            DishDto dishDto = new DishDto();
            // 把每一数据复制到DTO中
            BeanUtils.copyProperties(dish, dishDto);
            // 根据每一个ID查询每一个菜品
            Category category = categoryService.getById(dish.getCategoryId());
            // 设置菜品名称
            dishDto.setCategoryName(category.getName());
            // 添加到List中
            dishDtos.add(dishDto);
        }
        // 把List赋值给DTOPage
        dishDtoPage.setRecords(dishDtos);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> selectById(@PathVariable("id") Long id) {
        DishDto dishDto = dishService.getByIdWithDishAndFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateByIdWithFlavor(dishDto);
        Set<Object> keys = redisTemplate.keys("dish_*");
        if (keys != null) {
            redisTemplate.delete(keys);
        }
        return R.success("修改成功");
    }

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam("ids") Long[] ids) {
        dishService.disableById(status, ids);
        Set<Object> keys = redisTemplate.keys("dish_*");
        if (keys != null) {
            redisTemplate.delete(keys);
        }
        return R.success("状态修改成功");
    }

    @DeleteMapping
    public R<String> deleteById(@RequestParam("ids") Long[] ids) {
        dishService.removeById(ids);
        Set<Object> keys = redisTemplate.keys("dish_*");
        if (keys != null) {
            redisTemplate.delete(keys);
        }
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> listDish(@RequestParam("categoryId") Long categoryId) {
        String redisKey = "dish_" + categoryId;
        R<List<DishDto>> r = (R<List<DishDto>>) redisTemplate.opsForValue().get(redisKey);
        if(r != null){
            return r;
        }
        List<DishDto> dishList = dishService.listByCategoryId(categoryId);
        redisTemplate.opsForValue().set(redisKey,R.success(dishList));
        return R.success(dishList);
    }

}
